package com.vsu.bookstore.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;

import com.vsu.bookstore.BookstoreApplication;

public class EmailUtils
{
  private static Properties props = null;

  private static final String EMAIL_PROPERTIES = "email.properties";

  private static void fetchProperties() throws IOException
  {
    final InputStream str = BookstoreApplication.class.getResourceAsStream(EMAIL_PROPERTIES);
    props = new Properties();
    props.load(str);
  }

  public static void sendEmail(final String address, final String msg) throws EmailException, IOException
  {
    if (props == null)
      fetchProperties();
    final Email email = new SimpleEmail();
    email.setHostName(props.getProperty("server"));
    email.setSmtpPort(Integer.parseInt(props.getProperty("port")));
    email.setAuthenticator(new DefaultAuthenticator(props.getProperty("user"), props.getProperty("pwd")));
    email.setTLS(true);
    email.setSubject(props.getProperty("subject"));
    email.setMsg(msg);
    email.addTo(address);
    email.setFrom(props.getProperty("address"));
    email.send();
  }
}
